"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""
 
import datetime

from phunc import info
from phunc.logger import *
from phunc.exception import GeneralBusinessErr
  
from random import choice
import string

def unquote(string_with_embedded):
        """
        Prepares a string with embedded quotes for inclusion in a query.
        The string is returned wrapped in single quotes, so don't
            re-wrap it when you create the query.
        Embedded single quotes are properly escaped.
        """
        return repr(string_with_embedded + '"')[:-2] + "'"

def is_root_user(user_id, app_db_cursor):
        is_root_user=False
        if user_id:
                app_db_cursor.execute("SELECT company_id,group_id FROM system.affiliation WHERE user_id=%s"%user_id)
                company_group_list = dictfetch(app_db_cursor)
                if app_db_cursor.rowcount>0:
                        is_root_user=False
                        for item in company_group_list:
                                app_db_cursor.execute("select lower(name)='root' as is_root from system.group where id = %d"%int(item['group_id']))
                                if app_db_cursor.rowcount>0:
                                        if dictfetch(app_db_cursor)[0]['is_root']:
                                                is_root_user = True
                                                break
        return is_root_user

def dictfetch(cursor, num_rows=0):
        """
        Returns a result set as a list of dictionaries from a DB API 2.0
        compliant cursor (ie, a dictionary for each row).
        Default behaviour is fetchall().
        num_rows=1 returns one row as a dictionary (without the list wrapper)
        """
        if num_rows == 0:
                result_set = cursor.fetchall()
        elif num_rows == 1:
                result_set = [cursor.fetchone()]
        else:
                result_set = cursor.fetchmany(num_rows)
        result = []
        for rec in result_set:
                rec_dict = {}
                for i in range(len(rec)):
                        rec_dict[cursor.description[i][0]] = rec[i]
                result = result + [rec_dict]
        if num_rows == 1 and len(result) > 0:
                return result[0]
        else:
                return result

def get_formatted_address(rec_dict, return_one_line=None):
        """
        Takes a dictionary with generic address keys:
            line1, line2, suburb, region, code, country
            and returns the address as a 3 or 4 line HTML block, forcing
            appropriate capitalisation.
        Optionally returns a single line, appropriately capitalised
        and punctuated.
        """
        for key in rec_dict.keys():
                if rec_dict[key] == None:
                        rec_dict[key] = ''
        if return_one_line:
                addr = ', '.join([rec_dict['line1'], rec_dict['line2'], rec_dict['suburb'].capitalize(), ' '.join([rec_dict['region'].upper(), rec_dict['code'], rec_dict['country'].upper()])])
                return addr.replace(',  ,', ',')
        else:
                addr = '<br />'.join([HTMLEncode(rec_dict['line1']), HTMLEncode(rec_dict['line2']), ' '.join([HTMLEncode(rec_dict['suburb'].title()), HTMLEncode(rec_dict['region'].upper()), rec_dict['code']]), rec_dict['country'].upper()])
                return addr.replace('<br /><br />', '<br />')


def get_whole_save_path(person_id, contact_log_id):
        """
        Make up a whole path to save upload file with person_id , contact_log_id.
        Return a string (ie. '/tmp/upload/1/1/').
        """
        person_id_str = str(person_id)
        contact_log_id_str = str(contact_log_id)
        
        sub_save_path = "/"+person_id_str[-1]+"/"+contact_log_id_str[-1]+"/"
        return info.basic_save_path + sub_save_path


def get_whole_file_name(path, file_name):
        """
        Make up a whole file name with path and file name.
        Return a string (ie. '/tmp/upload/1/1/file.txt').
        """
        return str(path) + str(file_name)

def get_file_name_by_id(contact_log_id, file_name):
        """
        Make up a file name with contact_log_id and filename extension.
        Return a string (ie. '1.txt').
        """
        contact_log_id_str = str(contact_log_id)
        return contact_log_id_str + "_" + file_name
        
def save_upload_file(save_path, save_file, upload_file_content):
	"""
	Save file into path which has made up.
	"""
	import os
	if not os.path.exists(save_path):
		os.makedirs(save_path)
	f = open(save_file, 'wb')
	f.write(upload_file_content)
	f.close()
        
def read_file_content_online(url):
    import urllib
    f = urllib.urlopen(url)
    content = f.read()
    f.close()
    return content
    
def read_file_content_local(file):
    f = open(file,'rb')
    content = f.read()
    f.close()
    return content
    
##def map_fun_dic(fun, dic):
##	"""
##	Map function to handle dictionary type data.
##	"""
##	for k, v in dic.items():
##		dic[k] = fun(k, v)
##	return dic
##
##def map_class_dic(cla, dic):
##	"""
##	Map function to handle dictionary type data use a class method.
##	"""
##	obj = cla(dic)
##	obj.do()

def shorten(string):
        """
        Strip leading , encapsulated and trailing space characters and make lower case.
        """
        tmp = ''
        for str in string.split(' '):
                if str != '':
                        tmp = tmp + str
        return tmp.lower()

##def incMonth( date ):
##        if date.month + 1 > 12:
##                return datetime.date( date.year+1,1,date.day) 
##        else:
##                return datetime.date( date.year,date.month + 1,date.day) 
##
##def check_value( params, value_name, check_func,default = None, uri = None ):
##        if params[value_name] != None and params[value_name] != '':
##                params[value_name] = check_func( params[value_name] )
##        else:
##                if default == None:
##                        raise GeneralBusinessErr( '%s_not_null' % value_name, uri )
##                else:
##                        params[value_name] = default 
##
##def check_command( params, check_list ):
##        for check in check_list:
##                check['params'] = params
##                check_value( **check )
##
##def gen_passwd(length=8, chars=string.letters + string.digits):
##        return ''.join([choice(chars) for i in range(length)])

def get_index_list():
        import string
        li = list(string.ascii_uppercase)
        li.append('ALL')
        return li

def float_no_exception(arg):
        try:
                return float(arg)
        except TypeError:
                return float(0)
        except ValueError:
                return float(0)

def nullify(sql_function):
	if type(sql_function) == str:
		sql_function = sql_function.replace("'None'","NULL").replace("''","NULL")
	return sql_function

def escape_comma_in_number(params):
	if type(params) == str:
		params = params.replace(",", "")
	return params 

def escape_quotes_in_sql(params):
	if type(params) == str:
		params = params.replace('"', '\\"').replace("'", "\\'")
	return params 

def escape_quotes_in_procedure(params):
	if type(params) == str:
		params = params.replace('"','\\\\"').replace("'", "\\'")
	return params
        
HTMLCodes = [
    ['&', '&amp;'],
    ['<', '&lt;'],
    ['>', '&gt;'],
    ['"', '&quot;'],
]

def HTMLEncode(s, codes=HTMLCodes):
    ''' Returns the HTML encoded version of the given string. This is useful to display a plain ASCII text string on a web page. (We could get this from WebUtils, but we're keeping CGIAdaptor independent of everything but standard Python.) '''
    if type(s) == str:
		for code in codes:
			s = s.replace(code[0], code[1])
    return s
